'use strict';

const fs = require('fs');
const url = require('url');
const {chromium, firefox} = require('playwright');
const got = require('../utils/got');
const cheerio = require('cheerio');
const chinese = require('chinese-simple2traditional');

const Service = require('egg').Service;

class HotsearchSvc extends Service {

  async hotsearchAll() {
    const {ctx} = this;
    try {
      let total_hot_old = await ctx.service.cacheSvc.get('hotsearch');

      let hot_baidu_new = await ctx.service.hotsearchSvc.hotBaidu();
      let hot_weibo_new = await ctx.service.hotsearchSvc.hotWeibo();
      let hot_zhihu_new = await ctx.service.hotsearchSvc.hotZhihu();


      let total_hot = {
        'baidu': hot_baidu_new.list.length > 0 ? hot_baidu_new : total_hot_old['baidu'],
        'weibo': hot_weibo_new.list.length > 0 ? hot_weibo_new : total_hot_old['weibo'],
        'zhihu': hot_zhihu_new.list.length > 0 ? hot_zhihu_new : total_hot_old['zhihu'],
      }

      await ctx.service.cacheSvc.del('hotsearch');
      await ctx.service.cacheSvc.setex('hotsearch', total_hot, 60 * 60 * 24 * 365 * 100);
      ctx.logger.info('hotsearch cache success');
    } catch (e) {
      ctx.logger.error('热搜榜出错', e);
      ctx.helper.dd_warn('热搜榜出错' + e.message);
    }
  }

  async hotBaidu() {
    let result;

    let param = {
      url: 'https://top.baidu.com/board?tab=realtime',
      topic_info: {
        tab: 'hotsearch',
        boards: ['百度']
      },
      selector_info: {
        box: '.category-wrap_iQLoo.horizontal_1eKyQ',
        title: '.c-single-text-ellipsis',
        is_top: '.top-icon_15tUE',
        other: '.c-text.hot-tag_1G080'
      },
    };

    let topics = await this.service.commonSvc.commonLight(param);

    topics = topics.map(t => {
      return {
        title: t.title,
        link: `https://www.baidu.com/s?wd=${encodeURIComponent(t.title)}`,
        is_top: t.is_top,
        other: t.other
      }
    });

    if (topics[0] && topics[0].is_top) {
      result = {top: topics.slice(0, 1), list: topics.slice(1, 21)};
    } else {
      result = {list: topics.slice(0, 20)};
    }
    this.cleanObject(result);

    if (result.list.length > 0) {
      this.logger.info('baidu hotsearch success');
    } else {
      this.ctx.helper.dd_warn('百度热搜出错');
    }

    return result;
  }

  async hotWeibo() {
    let result;

    let param = {
      url: 'https://s.weibo.com/top/summary?cate=realtimehot',
      topic_info: {
        tab: 'hotsearch',
        boards: ['微博']
      },
      selector_info: {
        box: '#pl_top_realtimehot > table > tbody > tr',
        title: '.td-02 > a',
        content: '.td-02 > a',
        is_top: '.icon-top',
        other: '.td-03 > i'
      },
    };

    let topics = await this.service.commonSvc.commonFetch(param);

    topics = topics.filter(t => t.content != 'javascript:void(0);').map(t => {
      return {title: t.title, link: t.content, is_top: t.is_top, other: t.other};
    });

    if (topics[0] && topics[0].is_top) {
      result = {top: topics.slice(0, 1), list: topics.slice(1, 21)};
    } else {
      result = {list: topics.slice(0, 20)};
    }
    this.cleanObject(result);

    if (result.list.length > 0) {
      this.logger.info('weibo hotsearch success');
    } else {
      this.ctx.helper.dd_warn('微博热搜出错');
    }

    return result;

  }


  async hotJinri() {
    let result;

    let param = {
      url: 'https://www.toutiao.com/',
      topic_info: {
        tab: 'hotsearch',
        boards: ['今日头条']
      },
      selector_info: {
        box: 'div.ttp-hot-board > ol > li',
        title: '.article-item > p',
        content: '.article-item',
        is_top: '.icon-stick',
        is_hot: 'i.news-icon.hot',
        is_new: 'i.news-icon.new'
      },
    };

    let topics = await this.service.commonSvc.commonFetch(param);

    if (topics.length > 0) {
      param.click = 'button.refresh';
      let topics_page2 = await this.service.commonSvc.commonFetch(param);
      topics = topics.concat(topics_page2);
    }

    topics = topics.map(t => {
      let other;
      if (t.is_hot) {
        other = '热';
      } else if (t.is_new) {
        other = '新';
      }
      return {title: t.title, link: t.content, is_top: t.is_top, other: other}
    });

    if (topics[0] && topics[0].is_top) {
      result = {top: topics.slice(0, 1), list: topics.slice(1, 16)};
    } else {
      result = {list: topics.slice(0, 16)};
    }
    this.cleanObject(result);

    if (result.list.length > 0) {
      this.logger.info('jinri hotsearch success');
    } else {
      this.ctx.helper.dd_warn('今日头条热搜出错');
    }

    return result;
  }


  async hotZhihu() {
    let result;

    let param = {
      url: 'https://www.zhihu.com/billboard',
      topic_info: {
        tab: 'hotsearch',
        boards: ['知乎']
      },
      selector_info: {
        box: '.HotList-item',
        title: '.HotList-itemTitle',
      },
    };

    let topics = await this.service.commonSvc.commonLight(param);

    topics = topics.map(t => {
      return {title: t.title, link: `https://www.zhihu.com/search?type=content&q=${encodeURIComponent(t.title)}`}
    });

    result = {list: topics.slice(0, 20)};
    this.cleanObject(result);

    if (result.list.length > 0) {
      this.logger.info('zhihu hotsearch success');
    } else {
      this.ctx.helper.dd_warn('知乎热搜出错');
    }

    return result;
  }


  async hotFengwen() {
    let result;

    let param = {
      url: 'https://user.guancha.cn/',
      topic_info: {
        tab: 'hotsearch',
        boards: ['观察者']
      },
      selector_info: {
        box: 'ul.fengwen-most-hot > li',
        title: 'a',
        content: 'a',
      },
    };

    let topics = await this.service.commonSvc.commonLight(param);

    topics = topics.map(v => {
      return {title: v.title, link: v.content}
    });

    if (topics[0] && topics[0].is_top) {
      result = {top: topics.slice(0, 1), list: topics.slice(1, 16)};
    } else {
      result = {list: topics.slice(0, 16)};
    }
    this.cleanObject(result);

    if (result.list.length > 0) {
      this.logger.info('观察者 hotsearch success');
    } else {
      this.ctx.helper.dd_warn('观察者热搜出错');
    }

    return result;
  }


  cleanObject(obj) {
    for (const key in obj) {
      obj[key] = obj[key].map(v => {
        let r = {title: v.title, link: v.link};
        if (v.other) {
          r.other = v.other;
        }
        return r;
      });
    }
  }

}

module.exports = HotsearchSvc;
